import config from "../../config/index";
const {
	PrintLevels: {
		INFO,
		DEBUG,
		ERROR
	}
} = require("../../config/configEnum");
import {
	addNormalNotificationObserver,
	postNotification,
	removeNotificationObserver
} from "./notificationCenter";
import {
	dateFormat,
	getDateModel
} from "./timeUtil";
const KEY_NOTIFICATION_APPEND_LOG = "notification_key_append_log";
const KEY_NOTIFICATION_OPEN_LOG = "notification_key_open_log";
const KEY_STORAGE_OPEN_LOG = "open_log";

/** info 打印 */
function printInfo(...args) {
	if (config["Print_Level"] <= INFO) {
		console.log("INFO =>", ...args);
	}
	if (isLogOpen()) {
		recordLog(INFO, ...args);
	}
}
/** debug 打印 */
function printDebug(...args) {
	if (config["Print_Level"] <= DEBUG) {
		console.debug("DEBUG =>", ...args);
	}
	if (isLogOpen()) {
		recordLog(DEBUG, ...args);
	}
}
/** error 打印 */
function printError(...args) {
	if (config["Print_Level"] <= ERROR) {
		console.error("ERROR =>", ...args);
	}
	if (isLogOpen()) {
		recordLog(ERROR, ...args);
	}
}

/** ========================= 日志记录 ========================== */

class LogModel {
	constructor(level, log) {
		this.date = getDateModel(new Date());
		this.level = level;
		this.log = log;
	}
	getLevelName() {
		let s = {
			[`${INFO}`]: 'INFO',
			[`${DEBUG}`]: 'DEBUG',
			[`${ERROR}`]: 'ERROR',
		}
		return s[this.level];
	}
	getLogStr() {
		return JSON.stringify(this.log);
	}
	getLogTime() {
		return dateFormat(this.date.date, "yyyy-MM-dd HH:mm:ss.S")
	}
}

function openLog(open) {
	uni.setStorageSync(KEY_STORAGE_OPEN_LOG, open);
	if (!open) {
		DEBUG_INFO_LIST = [];
	}
	postNotification(KEY_NOTIFICATION_OPEN_LOG, open);
}

function watchLogOpen(callback, observer) {
	if (typeof callback == "function") callback(uni.getStorageSync(KEY_STORAGE_OPEN_LOG));
	addNormalNotificationObserver(KEY_NOTIFICATION_OPEN_LOG, (open) => {
		if (typeof callback == 'function') callback(open)
	}, observer);
}

function stopWatchLogOpen(observer) {
	removeNotificationObserver(KEY_NOTIFICATION_OPEN_LOG, observer);
}

function isLogOpen() {
	return uni.getStorageSync(KEY_STORAGE_OPEN_LOG)
}

let DEBUG_INFO_LIST = [];
/** 记录 debug 页面数据 */
function recordLog(level, ...args) {
	let log = new LogModel(level, args);
	DEBUG_INFO_LIST.unshift(log);
	postNotification(KEY_NOTIFICATION_APPEND_LOG, DEBUG_INFO_LIST);
}

function watchDebugInfoList(callback, observer) {
	if (typeof callback == 'function') callback(DEBUG_INFO_LIST);
	addNormalNotificationObserver(KEY_NOTIFICATION_APPEND_LOG, () => {
		if (typeof callback == 'function') callback(DEBUG_INFO_LIST);
	}, observer)
}

function stopWatchDebugInfoList(observer) {
	removeNotificationObserver(KEY_NOTIFICATION_APPEND_LOG, observer);
}

module.exports = {
	/** print */
	printInfo,
	printDebug,
	printError,

	/** log */
	openLog,
	watchLogOpen,
	stopWatchLogOpen,
	isLogOpen,
	recordLog,
	watchDebugInfoList,
	stopWatchDebugInfoList,
}